import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xin_he/utils/xin_he_toast.dart';
import 'package:xin_he/utils/xin_he_user_data.dart';

import '../../utils/xh_styles.dart';
import '../../utils/xin_he_event_bus.dart';
import '../../utils/xin_he_image.dart';
import '../../utils/xin_he_storage.dart';
import '../adopt/xin_he_adopt/xin_he_adopt_view.dart';
import '../category/xin_he_category/xin_he_category_view.dart';
import '../home/xin_he_home/xin_he_home_view.dart';
import '../mine/xin_he_mine/xin_he_mine_view.dart';
import '../shopping_car/xin_he_shopping_car/xin_he_shopping_car_view.dart';

class XinHeRootPage extends StatefulWidget  {
  const XinHeRootPage({Key? key}) : super(key: key);

  @override
  State<XinHeRootPage> createState() => _XinHeRootPageState();
}

class _XinHeRootPageState extends State<XinHeRootPage> with AutomaticKeepAliveClientMixin {

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
  //上次点击时间-根路由导航返回拦截-防止误操作退出
  DateTime? _lastPressedAt;

  //当前点击的tab
  ValueKey currentTab = const ValueKey(0);
  PageController pageController = PageController();
  BuildContext? tabContext;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  var ss =  xinHeUserData.appLoginState.value;
  xinHeUserData.updateAllData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: WillPopScope(
        onWillPop: () async {
          if (_lastPressedAt == null ||
              DateTime.now().difference(_lastPressedAt!) >
                  const Duration(seconds: 2)) {
            //两次点击间隔超过2秒则重新计时
            _lastPressedAt = DateTime.now();
            XinHeToast.bottom('再按一次退出APP!');
            return false;
          }
          exit(0);
        },
        child: PageView(
          physics: const NeverScrollableScrollPhysics(),
          controller: pageController,
          onPageChanged: (int newIndex) {
            // 设置状态栏样式
            //   Styles.setSystemBackStyle(
            //   color: Colors.transparent,
            //   isLight: true,
            //   isRootStyle: true,
            // );
          },
          children: [
            XinHeHomePage(),
            XinHeCategoryPage(),
            XinHeAdoptPage(),
            XinHeShoppingCarPage(),
            const XinHeMinePage()
            // Container(),
          ],
        ),
      ),
      bottomNavigationBar: bottomBar(),
    );

  }


  ///底部tab初始化
  Widget bottomBar() {
    //标题集合
    List<String> titleList = ['首页', '分类', '认养', '购物车','我的'];
    //icon图标
    List<List<String>> iconList = [
      [
        'assets/images/tabs/home_selected.png',
        'assets/images/tabs/home_unselected.png',
      ],
      [
        'assets/images/tabs/category_selected.png',
        'assets/images/tabs/category_unselected.png',
      ],
      [
        'assets/images/tabs/adopt_selected.png',
        'assets/images/tabs/adopt_unselected.png',
      ],
      [
        'assets/images/tabs/car_selected.png',
        'assets/images/tabs/car_unselected.png',
      ],
      [
        'assets/images/tabs/mine_selected.png',
        'assets/images/tabs/mine_unselected.png',
      ],
    ];
    //选中的字体颜色
    Color sColor = XinHeStyle.mainGreenColor;
    //未选中的字体颜色
    Color uColor = XinHeColor('#AFAFBC');



    ///tabBar点击
    void outsideChangeBar(ValueKey key) {

      pageController.jumpToPage(key.value);
      currentTab = key;
      ///刷新
      (tabContext as Element?)?.markNeedsBuild();

      bus.emit(XinHeStorage.KNeedRefresh,key.value);


    }

    ///生成单个bar
    Widget createBar(ValueKey key, double width, String title, List icon) {
      return GestureDetector(
        onTap: () => outsideChangeBar(key),
        child: Container(
          width: width,
          color: Colors.transparent,
          child: Column(
            children: [
              Stack(
                children: [
                  Container(
                    color: Colors.transparent,
                    margin: const EdgeInsets.only(
                      top: 7,
                    ),
                    width: 24,
                    height: 24,
                    child: 
                        XinHeAssetImage(key.value == currentTab.value ? icon[0] : icon[1],fit: BoxFit.contain,),
                  ),
                ],
              ),
              Container(
                margin: const EdgeInsets.only(
                  top: 4,
                ),
                child: Text(
                  title,
                  style: TextStyle(
                      fontSize: 11,
                      fontWeight: key.value == currentTab.value
                          ? FontWeight.w600
                          : FontWeight.w500,
                      // fontFamily: "DINPro",
                      color: key.value == currentTab.value ? sColor : uColor),
                  strutStyle: StrutStyle(
                    fontSize: 11,
                    forceStrutHeight: true,
                    // fontFamily: "DINPro",
                    fontWeight: key.value == currentTab.value
                        ? FontWeight.w600
                        : FontWeight.w500,
                  ),
                ),
              ),
            ],
          ),
        ),
      );
    }



    return Container(
      decoration: const BoxDecoration(
          boxShadow: [BoxShadow(color: Color.fromARGB(102, 186, 190, 194), blurRadius: 10)],
          // borderRadius: BorderRadius.only(
          //     topLeft: Radius.circular(14), topRight: Radius.circular(14)),
          color: Colors.white),
      clipBehavior: Clip.hardEdge,
      child: BottomAppBar(
        color: Colors.white,
        child: Builder(
          builder: (context) {
            tabContext = context;
            return SizedBox(
              height: 60,
              child: Row(
                children: List.generate(
                    titleList.length,
                        (index) => createBar(
                      ValueKey(index),
                      Get.width / titleList.length,
                      titleList[index],
                      iconList[index],
                    )),
              ),
            );
          },
        ),
      ),
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    pageController.dispose();
  }

}
